package com.light.gulimall.product.service.impl;

import com.light.gulimall.product.dao.BrandDao;
import com.light.gulimall.product.dao.CategoryDao;
import com.light.gulimall.product.entity.BrandEntity;
import com.light.gulimall.product.entity.CategoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.light.common.utils.PageUtils;
import com.light.common.utils.Query;

import com.light.gulimall.product.dao.CategoryBrandRelationDao;
import com.light.gulimall.product.entity.CategoryBrandRelationEntity;
import com.light.gulimall.product.service.CategoryBrandRelationService;


@Service("categoryBrandRelationService")
public class CategoryBrandRelationServiceImpl extends ServiceImpl<CategoryBrandRelationDao, CategoryBrandRelationEntity> implements CategoryBrandRelationService {

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private CategoryDao categoryDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryBrandRelationEntity> page = this.page(
                new Query<CategoryBrandRelationEntity>().getPage(params),
                new QueryWrapper<CategoryBrandRelationEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存品牌与分类关联关系
     *
     * @param categoryBrandRelation {"brandId":1,"catelogId":2}
     */
    @Override
    public void saveCategoryBrandRelation(CategoryBrandRelationEntity categoryBrandRelation) {
        Long brandId = categoryBrandRelation.getBrandId();
        BrandEntity brandEntity = brandDao.selectById(brandId);
        if (brandEntity != null){
            categoryBrandRelation.setBrandName(brandEntity.getName());
        }
        Long catelogId = categoryBrandRelation.getCatelogId();
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null){
            categoryBrandRelation.setCatelogName(categoryEntity.getName());
        }
        this.save(categoryBrandRelation);
    }

    /**
     * 获取分类关联的品牌
     *
     * @param catId 分类ID
     * @return 查询结果集
     */
    @Override
    public List<CategoryBrandRelationEntity> getBrandsList(Long catId) {
        QueryWrapper<CategoryBrandRelationEntity> categoryBrandRelationEntityQueryWrapper = new QueryWrapper<>();
        categoryBrandRelationEntityQueryWrapper.eq("catelog_id", catId);
        return list(categoryBrandRelationEntityQueryWrapper);
    }

}